package com.example.blog.controller;

import com.example.blog.model.BlogInfo;
import com.example.blog.model.Result;
import com.example.blog.service.BlogService;
import com.example.blog.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Home-pc
 * Date: 2024-02-26
 * Time: 14:46
 */
@RequestMapping("/blog")
@RestController
public class BlogController {

    @Autowired
    private BlogService blogService;
    /**
     * 获取博客列表
     */
    @RequestMapping("/getlist")
    public List<BlogInfo> getBlogList(){
        return  blogService.getBlogList();
    }

    /**
     * 获取博客详情页
     */
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId,HttpServletRequest request){
        BlogInfo blogInfo = blogService.getBlogDetail(blogId);
        //判断作者是否为登录用户,从登录用户的token中拿到用户的id和博客信息中的用户的id进行对比

        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if(userId != null && userId == blogInfo.getUserId()){
            blogInfo.setLoginUser(true);
        }
        return blogInfo;
    }

    /**
     * 发布博客
     */
    @RequestMapping("/add")
    public Result publishBlog(String title, String content, HttpServletRequest request){
        //需要userId，title，content
        //从token中获取userId
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if(userId == null || userId<0){
            return  Result.fail("用户未登录",false);

        }
        //插入博客
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setUserId(userId);
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogService.insertBlog(blogInfo);
        return  Result.success(true);
    }

    /**
     * 修改/编辑博客
     */
    @RequestMapping("/update")
    public boolean updateBlog(Integer id ,String title,String content){
        //需要博客的标题和内容，以及被更新的博客的id
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogInfo.setId(id);

        blogService.updateBlog(blogInfo);
        return true;
    }
}
